package com.wh.wisdomsite.xbox.core;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import javax.servlet.AsyncContext;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 配置XboxServlet
 * @Package com.wh.wisdomsite.xbox.common
 * @author 谢泽鹏
 * @date 2014年10月8日 下午4:02:14
 * @Copyright 个人版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2014
 * @version V1.0
 */
public class XboxServlet extends HttpServlet {


    private static final Log logger = LogFactory.getLog(XboxServlet.class);

    private ServiceDispatcher serviceDispatcher;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        AsyncContext context = request.startAsync();
        context.setTimeout(0);
        serviceDispatcher.execute(context);
        //System.out.println("执行完毕.异步检查");
        //serviceDispatcher.execute(request,response);
    }

    @Override
    public void init(ServletConfig servletConfig) throws ServletException {
        ApplicationContext applicationContext = getApplicationContext(servletConfig);
        serviceDispatcher = applicationContext.getBean(ServiceDispatcher.class);
        if (serviceDispatcher == null) {
            logger.error("在容器启动时,未找到" + ServiceDispatcher.class.getName() + "," +"请检查是否配置<xbox:service-dispatcher/>标签");
        }
    }

    private ApplicationContext getApplicationContext(ServletConfig servletConfig) {
        return (ApplicationContext) servletConfig.getServletContext()
                .getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
    }
}
